# -*- coding: utf-8 -*-
"""
@Time: 2025/1/10 11:41
@Auth: Zhang Hongxing
@File: analysis_routes.py
@Note:   
"""
import os
from flask import Blueprint, request, jsonify
from typing import List, Dict
from backend.services.analysis_service import get_essay_history_from_files, get_essay_analysis,get_essay_analysis2, compare_essays, \
    get_user_progress, get_analysis_data,get_purpose_fit_analysis,get_article_structure_analysis,get_vocabulary_diversity_analysis
from backend.services.analysis_service import preprocess_text,get_essay_detail
from backend.model.scoring_model import score_essay,score_essay_with_chatgpt
from functools import wraps
import jwt
from datetime import datetime, timedelta
# 配置信息
SECRET_KEY = 'your_secret_key'
TOKEN_EXPIRATION = 24 * 60 * 60  # 24小时过期


def decode_token(token):
    """
    解码JWT令牌
    """
    try:
        # 明确指定算法和验证选项
        payload = jwt.decode(
            token,
            SECRET_KEY,
            algorithms=['HS256'],
            options={
                'verify_exp': True,  # 验证过期时间
                'verify_iat': True,  # 验证签发时间
            }
        )
        return payload
    except jwt.ExpiredSignatureError:
        print("令牌已过期")
        return None
    except jwt.InvalidTokenError as e:
        print(f"无效的令牌: {str(e)}")
        return None
    except Exception as e:
        print(f"令牌解析错误: {str(e)}")
        return None


def token_required(f):
    """
    Token验证装饰器
    """

    @wraps(f)
    def decorated(*args, **kwargs):
        # 获取Authorization头
        auth_header = request.headers.get('Authorization')
        if not auth_header:
            return jsonify({
                "code": 401,
                "message": "缺少Authorization头信息"
            }), 401

        # 验证Bearer格式
        parts = auth_header.split()
        if parts[0].lower() != 'bearer' or len(parts) != 2:
            return jsonify({
                "code": 401,
                "message": "无效的Authorization格式"
            }), 401

        token = parts[1]
        payload = decode_token(token)

        if payload is None:
            return jsonify({
                "code": 401,
                "message": "无效或过期的令牌"
            }), 401

        try:
            # 验证令牌中的必要信息
            if 'user_id' not in payload:
                return jsonify({
                    "code": 401,
                    "message": "令牌缺少用户信息"
                }), 401

            # 验证令牌是否过期
            exp_timestamp = payload.get('exp')
            if exp_timestamp is None:
                return jsonify({
                    "code": 401,
                    "message": "令牌缺少过期时间"
                }), 401

            current_timestamp = datetime.utcnow().timestamp()
            if current_timestamp > exp_timestamp:
                return jsonify({
                    "code": 401,
                    "message": "令牌已过期"
                }), 401

            # 将用户信息添加到请求上下文
            return f(payload['user_id'], *args, **kwargs)

        except Exception as e:
            return jsonify({
                "code": 401,
                "message": f"令牌验证失败: {str(e)}"
            }), 401

    return decorated

# 定义路由蓝图
analysis_routes = Blueprint('analysis_routes', __name__)

#【接口2.1.3】GET /essay/{essay_id} # 获取作文详情
from flask import request, jsonify
from functools import wraps

@analysis_routes.route('/essay', methods=['GET'])
@token_required
def get_essay(user_id):
    """获取作文详情接口（基于查询参数）"""
    try:
        # 获取查询参数
        essay_id = request.args.get('essay_id')
        version_id = request.args.get('version_id')

        # 参数校验
        if not essay_id:
            return jsonify({
                'code': 400,
                'message': '缺少 essay_id 参数',
                'data': None
            }), 400

        if not version_id:
            return jsonify({
                'code': 400,
                'message': '缺少 version_id 参数',
                'data': None
            }), 400

        try:
            version_id = int(version_id)  # 确保 version_id 是整数
        except ValueError:
            return jsonify({
                'code': 400,
                'message': 'version_id 必须是整数',
                'data': None
            }), 400

        # 调用 get_essay_detail 获取作文内容
        result = get_essay_detail(user_id, essay_id, version_id)

        # 处理错误响应
        if isinstance(result, tuple):
            return jsonify({
                'code': result[0],
                'message': result[1],
                'data': None
            }), result[0]

        # 正常返回作文详情
        return jsonify({
            'code': 200,
            'message': '获取作文详情成功',
            'data': result
        }), 200

    except Exception as e:
        print(f"[ERROR] 获取作文详情接口异常: {str(e)}")
        return jsonify({
            'code': 500,
            'message': '【接口2.1.3】获取作文详情失败',
            'data': None
        }), 500



#【接口2.1.4】GET /essay/history    # 获取历史作文列表
@analysis_routes.route('/essay/history', methods=['GET'])
@token_required
def get_history(user_id):
    """
    获取用户的历史作文列表
    :param user_id: 从token验证中获取的用户ID
    :return: 返回历史作文的JSON数据
    """
    try:
        # 直接使用从token_required装饰器传入的user_id
        essays = get_essay_history_from_files(user_id)

        # 如果没有找到作文，返回404
        if not essays:
            return jsonify({
                "code": 404,
                "message": "未找到历史作文"
            }), 404

        # 返回成功响应
        return jsonify({
            "code": 200,
            "message": "获取历史作文成功",
            "data": essays
        }), 200

    except Exception as e:
        # 捕获异常并返回服务器错误
        print(f"【接口2.1.4】获取历史作文失败: {e}")
        return jsonify({
            "code": 500,
            "message": "服务器内部错误"
        }), 500

# 【接口2.1.5】GET /essay/analysis    # 获取指定作文版本的分析数据
@analysis_routes.route('/essay/analysis', methods=['GET'])
@token_required
def get_analysis(user_id):
    """
    获取指定作文版本的分析数据
    :param user_id: 从token验证中获取的用户ID
    :return: 返回分析数据的JSON
    """
    try:
        essay_id = request.args.get('essay_id')
        version_id = request.args.get('version_id')

        if not essay_id or not version_id:
            return jsonify({
                "code": 400,
                "message": "缺少必要参数"
            }), 400

        # 获取分析数据
        analysis_data = get_analysis_data(user_id, essay_id, version_id)

        if not analysis_data:
            return jsonify({
                "code": 404,
                "message": "未找到分析数据"
            }), 404

        return jsonify({
            "code": 200,
            "message": "获取分析数据成功",
            "data": analysis_data
        }), 200

    except Exception as e:
        print(f"【接口2.1.4】获取分析数据失败: {e}")
        return jsonify({
            "code": 500,
            "message": "服务器内部错误"
        }), 500


# 【接口3.1.2】POST /model/preprocess  文本预处理
@analysis_routes.route('/model/preprocess', methods=['POST'])
@token_required
def preprocess_text_api(user_id):
    """
    文本预处理 API
    :return: 返回预处理后的单词列表（JSON格式）
    """
    try:
        # 获取请求中的文本参数
        data = request.get_json()
        text = data.get('text')

        if not text:
            return jsonify({"code": 400, "message": "缺少文本参数"}), 400

        # 调用文本预处理服务
        processed_text = preprocess_text(text)

        # 如果预处理失败
        if processed_text is None:
            return jsonify({"code": 500, "message": "文本预处理失败"}), 500

        # 返回成功响应，包含预处理后的数据
        return jsonify({
            "code": 200,
            "message": "文本预处理成功",
            "data": processed_text
        }), 200

    except Exception as e:
        # 捕获异常并返回服务器错误
        print(f"【接口3.1.2】文本预处理失败: {e}")
        return jsonify({"code": 500, "message": "服务器内部错误"}), 500

#【接口3.1.1】POST /model/score  模型评分
@analysis_routes.route('/model/score', methods=['POST'])
@token_required
def score_essay_api(user_id):
    """
    作文评分 API
    :return: 返回作文评分结果（JSON格式）
    """
    try:
        # 获取请求中的文本参数
        data = request.get_json()
        text = data.get('text')

        # 校验是否提供了作文文本
        if not text:
            return jsonify({"code": 400, "message": "缺少文本参数"}), 400

        # 调用评分函数进行评分
        result = score_essay(text)

        # 检查评分结果是否成功
        if result.get("score") == 0 and result.get("message") == "文本内容无效，无法评分":
            return jsonify({"code": 400, "message": "作文文本内容无效，无法评分"}), 400

        # 返回成功响应，包含评分结果
        return jsonify({
            "code": 200,
            "message": "评分成功",
            "data": result
        }), 200

    except Exception as e:
        # 捕获异常并返回服务器错误
        print(f"【接口3.1.1】作文评分失败: {e}")
        return jsonify({"code": 500, "message": "服务器内部错误"}), 500

# 【接口3.1.1】POST /bigmodel-gpt/score   # 调用大模型评分-chatGPT
from backend.model.scoring_model import score_essay_with_chatgpt
from backend.services.analysis_service import get_essay_detail  # 导入获取作文内容的方法
import os
import json
from datetime import datetime
from flask import request, jsonify

# 存储文件的目录
STORAGE_DIR = "../data/raw/score_data"
@analysis_routes.route('/bigmodel-gpt/score', methods=['POST'])
@token_required
def score_essay_api_chatGPT(user_id):
    """
    作文评分 API
    :return: 返回作文评分结果（JSON格式）
    """
    try:
        # 获取请求体中的作文ID和版本ID
        data = request.get_json()
        essay_id = data.get('essay_id')
        version_id = data.get('version_id')

        # 校验是否提供了作文 ID 和 版本 ID
        if not essay_id:
            return jsonify({"code": 400, "message": "缺少作文ID"}), 400
        if version_id is None:
            return jsonify({"code": 400, "message": "缺少版本ID"}), 400

        try:
            version_id = int(version_id)  # 确保 version_id 是整数
        except ValueError:
            return jsonify({"code": 400, "message": "版本ID必须是整数"}), 400

        # 调用 get_essay_detail 获取作文文本
        essay_content = get_essay_detail(user_id, essay_id, version_id)
        if isinstance(essay_content, tuple):
            return jsonify({"code": essay_content[0], "message": essay_content[1]}), essay_content[0]

        # 评分
        result = score_essay_with_chatgpt(essay_content["text"])

        # 检查评分结果是否成功
        if result.get("score") == 0 and result.get("message") == "文本内容无效，无法评分":
            return jsonify({"code": 400, "message": "作文文本内容无效，无法评分"}), 400

        # 获取当前时间
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        # 组织存储数据
        score_data = {
            "user_id": user_id,
            "essay_id": essay_id,
            "version_id": version_id,
            "timestamp": timestamp,
            "score": result["score"],
            "details": result["details"],  # 评分详情
        }

        # 返回成功响应
        return jsonify({
            "code": 200,
            "message": "评分成功",
            "data": score_data
        }), 200

    except Exception as e:
        # 捕获异常并返回服务器错误
        print(f"【接口3.1.1】chatGPT作文评分失败: {e}")
        return jsonify({"code": 500, "message": "服务器内部错误"}), 500

# 【接口3.1.1-1】POST /bigmodel-gpt-EN/score   # 调用大模型评分-chatGPT中文模型
from backend.model.scoring_model import score_essay_chatgpt_EN
from backend.services.analysis_service import get_essay_detail  # 导入获取作文内容的方法
import json
from datetime import datetime
from flask import request, jsonify

@analysis_routes.route('/bigmodel-gpt-EN/score', methods=['POST'])
@token_required
def score_essay_api_chatGPT_EN(user_id):
    """
    作文评分 API
    :return: 返回作文评分结果（JSON格式）
    """
    try:
        # 获取请求体中的作文ID、版本ID、语言参数和模型名称
        data = request.get_json()
        essay_id = data.get('essay_id')
        version_id = data.get('version_id')
        language = data.get('language', '中文')  # 默认为中文
        modelName = data.get('modelName')  # 默认为高考评分模型

        # 校验是否提供了作文 ID 和 版本 ID
        if not essay_id:
            return jsonify({"code": 400, "message": "缺少作文ID"}), 400
        if version_id is None:
            return jsonify({"code": 400, "message": "缺少版本ID"}), 400

        try:
            version_id = int(version_id)  # 确保 version_id 是整数
        except ValueError:
            return jsonify({"code": 400, "message": "版本ID必须是整数"}), 400

        # 调用 get_essay_detail 获取作文文本
        essay_content = get_essay_detail(user_id, essay_id, version_id)
        if isinstance(essay_content, tuple):
            return jsonify({"code": essay_content[0], "message": essay_content[1]}), essay_content[0]

        # 评分，传入model_name参数
        result = score_essay_chatgpt_EN(essay_content["text"], language, modelName)

        # 检查评分结果是否成功
        if result.get("score") == 0 and result.get("message") == "文本内容无效，无法评分":
            return jsonify({"code": 400, "message": "作文文本内容无效，无法评分"}), 400

        # 获取当前时间
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        # 组织存储数据
        score_data = {
            "user_id": user_id,
            "essay_id": essay_id,
            "version_id": version_id,
            "timestamp": timestamp,
            "score": result["score"],
            "model_used": result.get("model_used", modelName),  # 添加使用的模型信息
            "details": result["details"],  # 评分详情
        }

        # 返回成功响应
        return jsonify({
            "code": 200,
            "message": "评分成功",
            "data": score_data
        }), 200

    except Exception as e:
        # 捕获异常并返回服务器错误
        print(f"【接口3.1.1-1】chatGPT英文模型作文评分失败: {e}")
        return jsonify({"code": 500, "message": "服务器内部错误"}), 500


# 【接口3.1.1-2】POST /bigmodel-gpt-CHN/score   # 调用大模型评分-chatGPT中文模型
from backend.model.scoring_model import score_essay_chatgpt_CHN
from backend.services.analysis_service import get_essay_detail  # 导入获取作文内容的方法
import json
from datetime import datetime
from flask import request, jsonify

@analysis_routes.route('/bigmodel-gpt-CHN/score', methods=['POST'])
@token_required
def score_essay_api_chatGPT_CHN(user_id):
    """
    作文评分 API
    :return: 返回作文评分结果（JSON格式）
    """
    try:
        # 获取请求体中的作文ID、版本ID、语言参数和模型名称
        data = request.get_json()
        essay_id = data.get('essay_id')
        version_id = data.get('version_id')
        language = data.get('language', '中文')  # 默认为中文
        modelName = data.get('modelName')  # 默认为高考评分模型

        # 校验是否提供了作文 ID 和 版本 ID
        if not essay_id:
            return jsonify({"code": 400, "message": "缺少作文ID"}), 400
        if version_id is None:
            return jsonify({"code": 400, "message": "缺少版本ID"}), 400

        try:
            version_id = int(version_id)  # 确保 version_id 是整数
        except ValueError:
            return jsonify({"code": 400, "message": "版本ID必须是整数"}), 400

        # 调用 get_essay_detail 获取作文文本
        essay_content = get_essay_detail(user_id, essay_id, version_id)
        if isinstance(essay_content, tuple):
            return jsonify({"code": essay_content[0], "message": essay_content[1]}), essay_content[0]

        # 评分，传入model_name参数
        result = score_essay_chatgpt_CHN(essay_content["text"], language, modelName)

        # 检查评分结果是否成功
        if result.get("score") == 0 and result.get("message") == "文本内容无效，无法评分":
            return jsonify({"code": 400, "message": "作文文本内容无效，无法评分"}), 400

        # 获取当前时间
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        # 组织存储数据
        score_data = {
            "user_id": user_id,
            "essay_id": essay_id,
            "version_id": version_id,
            "timestamp": timestamp,
            "score": result["score"],
            "model_used": result.get("model_used", modelName),  # 添加使用的模型信息
            "details": result["details"],  # 评分详情
        }

        # 返回成功响应
        return jsonify({
            "code": 200,
            "message": "评分成功",
            "data": score_data
        }), 200

    except Exception as e:
        # 捕获异常并返回服务器错误
        print(f"【接口3.1.1-2】chatGPT中文模型作文评分失败: {e}")
        return jsonify({"code": 500, "message": "服务器内部错误"}), 500


# 【接口3.1.1-3】POST /bigmodel-gpt-FRANCE/score   # 调用大模型评分-chatGPT法语模型
from backend.model.scoring_model import score_essay_chatgpt_FRANCE
from backend.services.analysis_service import get_essay_detail  # 导入获取作文内容的方法
import json
from datetime import datetime
from flask import request, jsonify

@analysis_routes.route('/bigmodel-gpt-FRANCE/score', methods=['POST'])
@token_required
def score_essay_api_chatGPT_FRANCE(user_id):
    """
    作文评分 API
    :return: 返回作文评分结果（JSON格式）
    """
    try:
        # 获取请求体中的作文ID、版本ID、语言参数和模型名称
        data = request.get_json()
        essay_id = data.get('essay_id')
        version_id = data.get('version_id')
        language = data.get('language', '中文')  # 默认为中文
        modelName = data.get('modelName')  # 默认为高考评分模型

        # 校验是否提供了作文 ID 和 版本 ID
        if not essay_id:
            return jsonify({"code": 400, "message": "缺少作文ID"}), 400
        if version_id is None:
            return jsonify({"code": 400, "message": "缺少版本ID"}), 400

        try:
            version_id = int(version_id)  # 确保 version_id 是整数
        except ValueError:
            return jsonify({"code": 400, "message": "版本ID必须是整数"}), 400

        # 调用 get_essay_detail 获取作文文本
        essay_content = get_essay_detail(user_id, essay_id, version_id)
        if isinstance(essay_content, tuple):
            return jsonify({"code": essay_content[0], "message": essay_content[1]}), essay_content[0]

        # 评分，传入model_name参数
        result = score_essay_chatgpt_FRANCE(essay_content["text"], language, modelName)

        # 检查评分结果是否成功
        if result.get("score") == 0 and result.get("message") == "文本内容无效，无法评分":
            return jsonify({"code": 400, "message": "作文文本内容无效，无法评分"}), 400

        # 获取当前时间
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        # 组织存储数据
        score_data = {
            "user_id": user_id,
            "essay_id": essay_id,
            "version_id": version_id,
            "timestamp": timestamp,
            "score": result["score"],
            "model_used": result.get("model_used", modelName),  # 添加使用的模型信息
            "details": result["details"],  # 评分详情
        }

        # 返回成功响应
        return jsonify({
            "code": 200,
            "message": "评分成功",
            "data": score_data
        }), 200

    except Exception as e:
        # 捕获异常并返回服务器错误
        print(f"【接口3.1.1-3】chatGPT法语模型作文评分失败: {e}")
        return jsonify({"code": 500, "message": "服务器内部错误"}), 500


# 【接口3.1.1-4】POST /bigmodel-gpt-RUSSIA/score   # 调用大模型评分-chatGPT法语模型
from backend.model.scoring_model import score_essay_chatgpt_RUSSIA
from backend.services.analysis_service import get_essay_detail  # 导入获取作文内容的方法
import json
from datetime import datetime
from flask import request, jsonify

@analysis_routes.route('/bigmodel-gpt-RUSSIA/score', methods=['POST'])
@token_required
def score_essay_api_chatGPT_RUSSIA(user_id):
    """
    作文评分 API
    :return: 返回作文评分结果（JSON格式）
    """
    try:
        # 获取请求体中的作文ID、版本ID、语言参数和模型名称
        data = request.get_json()
        essay_id = data.get('essay_id')
        version_id = data.get('version_id')
        language = data.get('language', '中文')  # 默认为中文
        modelName = data.get('modelName')  # 默认为高考评分模型

        # 校验是否提供了作文 ID 和 版本 ID
        if not essay_id:
            return jsonify({"code": 400, "message": "缺少作文ID"}), 400
        if version_id is None:
            return jsonify({"code": 400, "message": "缺少版本ID"}), 400

        try:
            version_id = int(version_id)  # 确保 version_id 是整数
        except ValueError:
            return jsonify({"code": 400, "message": "版本ID必须是整数"}), 400

        # 调用 get_essay_detail 获取作文文本
        essay_content = get_essay_detail(user_id, essay_id, version_id)
        if isinstance(essay_content, tuple):
            return jsonify({"code": essay_content[0], "message": essay_content[1]}), essay_content[0]

        # 评分，传入model_name参数
        result = score_essay_chatgpt_RUSSIA(essay_content["text"], language, modelName)

        # 检查评分结果是否成功
        if result.get("score") == 0 and result.get("message") == "文本内容无效，无法评分":
            return jsonify({"code": 400, "message": "作文文本内容无效，无法评分"}), 400

        # 获取当前时间
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        # 组织存储数据
        score_data = {
            "user_id": user_id,
            "essay_id": essay_id,
            "version_id": version_id,
            "timestamp": timestamp,
            "score": result["score"],
            "model_used": result.get("model_used", modelName),  # 添加使用的模型信息
            "details": result["details"],  # 评分详情
        }

        # 返回成功响应
        return jsonify({
            "code": 200,
            "message": "评分成功",
            "data": score_data
        }), 200

    except Exception as e:
        # 捕获异常并返回服务器错误
        print(f"【接口3.1.1-4】chatGPT俄语模型作文评分失败: {e}")
        return jsonify({"code": 500, "message": "服务器内部错误"}), 500

# 【接口3.1.1-5】POST /bigmodel-gpt-SPAIN/score   # 调用大模型评分-chatGPT法语模型
from backend.model.scoring_model import score_essay_chatgpt_SPAIN
from backend.services.analysis_service import get_essay_detail  # 导入获取作文内容的方法
import json
from datetime import datetime
from flask import request, jsonify

@analysis_routes.route('/bigmodel-gpt-SPAIN/score', methods=['POST'])
@token_required
def score_essay_api_chatGPT_SPAIN(user_id):
    """
    作文评分 API
    :return: 返回作文评分结果（JSON格式）
    """
    try:
        # 获取请求体中的作文ID、版本ID、语言参数和模型名称
        data = request.get_json()
        essay_id = data.get('essay_id')
        version_id = data.get('version_id')
        language = data.get('language', '中文')  # 默认为中文
        modelName = data.get('modelName')  # 默认为高考评分模型

        # 校验是否提供了作文 ID 和 版本 ID
        if not essay_id:
            return jsonify({"code": 400, "message": "缺少作文ID"}), 400
        if version_id is None:
            return jsonify({"code": 400, "message": "缺少版本ID"}), 400

        try:
            version_id = int(version_id)  # 确保 version_id 是整数
        except ValueError:
            return jsonify({"code": 400, "message": "版本ID必须是整数"}), 400

        # 调用 get_essay_detail 获取作文文本
        essay_content = get_essay_detail(user_id, essay_id, version_id)
        if isinstance(essay_content, tuple):
            return jsonify({"code": essay_content[0], "message": essay_content[1]}), essay_content[0]

        # 评分，传入model_name参数
        result = score_essay_chatgpt_SPAIN(essay_content["text"], language, modelName)

        # 检查评分结果是否成功
        if result.get("score") == 0 and result.get("message") == "文本内容无效，无法评分":
            return jsonify({"code": 400, "message": "作文文本内容无效，无法评分"}), 400

        # 获取当前时间
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        # 组织存储数据
        score_data = {
            "user_id": user_id,
            "essay_id": essay_id,
            "version_id": version_id,
            "timestamp": timestamp,
            "score": result["score"],
            "model_used": result.get("model_used", modelName),  # 添加使用的模型信息
            "details": result["details"],  # 评分详情
        }

        # 返回成功响应
        return jsonify({
            "code": 200,
            "message": "评分成功",
            "data": score_data
        }), 200

    except Exception as e:
        # 捕获异常并返回服务器错误
        print(f"【接口3.1.1-5】chatGPT西班牙语模型作文评分失败: {e}")
        return jsonify({"code": 500, "message": "服务器内部错误"}), 500

# 【接口3.1.1-6】POST /bigmodel-gpt-JAPAN/score   # 调用大模型评分-chatGPT法语模型
from backend.model.scoring_model import score_essay_chatgpt_JAPAN
from backend.services.analysis_service import get_essay_detail  # 导入获取作文内容的方法
import json
from datetime import datetime
from flask import request, jsonify

@analysis_routes.route('/bigmodel-gpt-JAPAN/score', methods=['POST'])
@token_required
def score_essay_api_chatGPT_JAPAN(user_id):
    """
    作文评分 API
    :return: 返回作文评分结果（JSON格式）
    """
    try:
        # 获取请求体中的作文ID、版本ID、语言参数和模型名称
        data = request.get_json()
        essay_id = data.get('essay_id')
        version_id = data.get('version_id')
        language = data.get('language', '中文')  # 默认为中文
        modelName = data.get('modelName')  # 默认为高考评分模型

        # 校验是否提供了作文 ID 和 版本 ID
        if not essay_id:
            return jsonify({"code": 400, "message": "缺少作文ID"}), 400
        if version_id is None:
            return jsonify({"code": 400, "message": "缺少版本ID"}), 400

        try:
            version_id = int(version_id)  # 确保 version_id 是整数
        except ValueError:
            return jsonify({"code": 400, "message": "版本ID必须是整数"}), 400

        # 调用 get_essay_detail 获取作文文本
        essay_content = get_essay_detail(user_id, essay_id, version_id)
        if isinstance(essay_content, tuple):
            return jsonify({"code": essay_content[0], "message": essay_content[1]}), essay_content[0]

        # 评分，传入model_name参数
        result = score_essay_chatgpt_JAPAN(essay_content["text"], language, modelName)

        # 检查评分结果是否成功
        if result.get("score") == 0 and result.get("message") == "文本内容无效，无法评分":
            return jsonify({"code": 400, "message": "作文文本内容无效，无法评分"}), 400

        # 获取当前时间
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        # 组织存储数据
        score_data = {
            "user_id": user_id,
            "essay_id": essay_id,
            "version_id": version_id,
            "timestamp": timestamp,
            "score": result["score"],
            "model_used": result.get("model_used", modelName),  # 添加使用的模型信息
            "details": result["details"],  # 评分详情
        }

        # 返回成功响应
        return jsonify({
            "code": 200,
            "message": "评分成功",
            "data": score_data
        }), 200

    except Exception as e:
        # 捕获异常并返回服务器错误
        print(f"【接口3.1.1-6】chatGPT日语模型作文评分失败: {e}")
        return jsonify({"code": 500, "message": "服务器内部错误"}), 500


# 【接口3.3.1】POST /model/feedback   # 提交模型评分反馈
from backend.services.analysis_service import save_feedback

ESSAY_DATA_DIR = "../data/raw/essay_data"

@analysis_routes.route('/model/feedback', methods=['POST'])
@token_required
def feedback_api(user_id):
    try:
        # 获取请求参数
        data = request.get_json()
        essay_id = data.get("essay_id")
        version_id = data.get("version_id")
        feedback = data.get("feedback")
        suggestion = data.get("suggestion")

        # 参数校验
        if not essay_id or not version_id or not feedback:
            return jsonify({"code": 400, "message": "缺少必要参数"}), 400

        essay_path = os.path.join(ESSAY_DATA_DIR, f"{essay_id}.txt")
        if not os.path.exists(essay_path):
            return jsonify({"code": 404, "message": "作文不存在，反馈提交失败"}), 404

        # 调用 service 层保存反馈
        feedback_data = save_feedback(user_id, essay_id, version_id, feedback, suggestion)

        if not feedback_data:
            return jsonify({"code": 500, "message": "反馈提交失败"}), 500

        return jsonify({
            "code": 200,
            "message": "反馈提交成功，我们会根据您的意见改进模型。",
            "data": feedback_data
        }), 200

    except Exception as e:
        print(f"【接口3.3.1】评分反馈提交失败：{str(e)}")
        return jsonify({"code": 500, "message": "服务器内部错误"}), 500

# 【接口3.3.2】POST /system/feedback        #系统反馈
from backend.services.analysis_service  import system_feedback

@analysis_routes.route('/system/feedback', methods=['POST'])
@token_required
def system_feedback_api(user_id):
    """
    系统反馈接口
    :param user_id: 用户ID（从token中解析）
    :return: 返回反馈提交结果
    """
    try:
        # 获取请求参数
        data = request.get_json()
        essay_id = data.get("essay_id")
        version_id = data.get("version_id")
        overall_satisfaction = data.get("overall_satisfaction")
        rating_accuracy = data.get("rating_accuracy")
        user_experience = data.get("user_experience")
        feedback = data.get("feedback")
        name = data.get("name")
        phone = data.get("phone")
        email = data.get("email")

        # 参数校验
        if not all([overall_satisfaction, rating_accuracy, user_experience, feedback]):
            return jsonify({"code": 400, "message": "缺少必要参数"}), 400

        # 校验评分参数是否为整数且在1到5之间
        try:
            overall_satisfaction = int(overall_satisfaction)
            rating_accuracy = int(rating_accuracy)
            user_experience = int(user_experience)
            if not all(1 <= score <= 5 for score in [overall_satisfaction, rating_accuracy, user_experience]):
                return jsonify({"code": 400, "message": "评分参数必须是1到5之间的整数"}), 400
        except ValueError:
            return jsonify({"code": 400, "message": "评分参数必须是整数"}), 400

        # 调用 service 层构造反馈信息
        feedback_data = system_feedback(
            user_id=user_id,
            overall_satisfaction=overall_satisfaction,
            rating_accuracy=rating_accuracy,
            user_experience=user_experience,
            feedback=feedback,
            name=name,
            phone=phone,
            email=email
        )

        if not feedback_data:
            return jsonify({"code": 500, "message": "反馈提交失败"}), 500

        # 返回成功响应
        return jsonify({
            "code": 200,
            "message": "反馈提交成功，感谢您的宝贵意见！",
            "data": feedback_data
        }), 200

    except Exception as e:
        print(f"【接口3.3.2】系统反馈提交失败：{str(e)}")
        return jsonify({"code": 500, "message": "服务器内部错误"}), 500


#【接口4.1.1】GET /criteria/list  获取评分标准列表
import json
from collections import OrderedDict

@analysis_routes.route('/criteria/list', methods=['GET'])
@token_required
def get_score_standards(user_id):
    try:
        # 从txt文件中读取评分标准数据
        with open('standard/score_standards.txt', 'r', encoding='utf-8') as file:
            score_data = json.load(file)

        # 获取正常模型和GPT模型的评分标准
        normalmodel_score_standards = score_data.get('normalmodel', [])
        gpt_score_standards = score_data.get('gpt', [])

        # 返回成功响应
        return jsonify({
            "code": 200,
            "message": "获取评分标准列表成功",
            "normalmodel_standard": normalmodel_score_standards,
            "gpt_standard": gpt_score_standards
        }), 200

    except Exception as e:
        # 捕获异常并返回服务器错误
        print(f"【接口4.1.1】获取评分标准列表失败: {e}")
        return jsonify({"code": 500, "message": "服务器内部错误"}), 500


#【接口4.1.2】GET /criteria/detail/{id} 获取评分标准详情
# from collections import OrderedDict
# from flask import jsonify
# @analysis_routes.route('/criteria/detail/<int:id>', methods=['GET'])
# @token_required
# def get_rating_criteria_details(usr_id,id: int):
#     """
#     获取评分标准的详细信息。
#     :param id: 评分标准的唯一标识符
#     :return: 返回评分标准的详细信息字典，如果获取失败则返回None
#     """
#     try:
#         # 模拟评分标准数据，实际应用中可以从数据库或API获取
#         rating_criteria = {
#             1: OrderedDict([
#                 ("id", 1),
#                 ("name", "词汇多样性"),
#                 ("description", "计算独特单词的比例，衡量词汇丰富度"),
#                 ("criteria_details", [
#                     {"level": 1, "score": 2, "description": "语言不流畅，存在较多冗余或难以理解的部分。"},
#                     {"level": 2, "score": 4, "description": "语言较流畅，少量冗余或表达不清的部分。"},
#                     {"level": 3, "score": 6, "description": "语言流畅，表达清晰，几乎没有冗余或难以理解的部分。"}
#                 ])
#             ]),
#             2: OrderedDict([
#                 ("id", 2),
#                 ("name", "句子结构"),
#                 ("description", "分析句子完整性和复杂度"),
#                 ("criteria_details", [
#                     {"level": 1, "score": 2, "description": "句子不完整，存在语法错误，结构混乱。"},
#                     {"level": 2, "score": 4, "description": "句子结构一般，有部分语法错误或不够复杂。"},
#                     {"level": 3, "score": 6, "description": "句子结构合理，语法正确，表达清晰。"}
#                 ])
#             ]),
#             3: OrderedDict([
#                 ("id", 3),
#                 ("name", "文章长度"),
#                 ("description", "统计文章的单词数，评估文章的充分性"),
#                 ("criteria_details", [
#                     {"level": 1, "score": 2, "description": "文章过短，缺乏足够的内容。"},
#                     {"level": 2, "score": 4, "description": "文章长度适中，内容尚可。"},
#                     {"level": 3, "score": 6, "description": "文章内容丰富，字数充足，论点充分。"}
#                 ])
#             ])
#         }
#
#         # 根据id返回相应的评分标准详情
#         if id in rating_criteria:
#             return jsonify({
#                 "code": 200,
#                 "message": "获取评分标准详情成功",
#                 "data": rating_criteria[id]
#             }), 200
#         else:
#             raise ValueError("无效的评分标准ID")
#
#     except Exception as e:
#         print(f"【4.1.2接口】获取评分标准详情报错：{str(e)}")
#         return jsonify({"code": 500, "message": "服务器内部错误"}), 500
#【接口4.1.2】GET /criteria/detail/{model}/{criteria_id} 获取评分标准详情
@analysis_routes.route('/criteria/detail/<model>/<int:criteria_id>', methods=['GET'])
@token_required
def get_rating_criteria_details(user_id, model, criteria_id):
    """
    根据模型选择和评分标准 ID 获取评分标准的详细信息。
    """
    try:
        # 从txt文件中读取评分标准数据
        with open('standard/details.txt', 'r', encoding='utf-8') as file:
            score_data = json.load(file)

        # 根据模型选择获取对应的评分标准
        selected_model = score_data.get(model, [])

        # 找到指定ID的评分标准
        criteria_details = None
        for criteria in selected_model:
            if criteria['id'] == criteria_id:
                criteria_details = criteria
                break

        if not criteria_details:
            return jsonify({
                "code": 404,
                "message": f"评分标准ID {criteria_id} 在模型 {model} 中未找到"
            }), 404

        # 获取评分标准的详细信息（根据你提供的结构）
        rating_criteria = {
            "criteria_id": criteria_details["id"],
            "name": criteria_details["name"],
            "description": criteria_details["description"],
            "criteria_details": criteria_details["criteria_details"]
        }

        # 返回评分标准的详细信息
        return jsonify({
            "code": 200,
            "message": "获取评分标准详情成功",
            "data": rating_criteria
        }), 200

    except Exception as e:
        logging.error(f"获取评分标准详情失败：{str(e)}")
        return jsonify({"code": 500, "message": "服务器内部错误"}), 500


# 【接口5.1.1】POST /analysis/essay/{essay_id}/{version_id}   获取单篇作文分析
@analysis_routes.route('/analysis/essay', methods=['POST'])
@token_required
def essay_analysis_api(user_id):
    """
    作文分析 API
    :param user_id: 用户ID
    :return: 返回作文分析结果（JSON格式）
    """
    try:
        # 解析请求体 JSON
        data = request.get_json()
        if not data:
            return jsonify({"code": 400, "message": "请求体不能为空"}), 400

        # 获取请求参数
        essay_id = data.get("essay_id")
        version_id = data.get("version_id")
        essay_knowledge = data.get("essay_knowledge")
        knowledge = data.get("knowledge")
        modelName = data.get("modelName")

        # 校验必要参数
        if not all([essay_id, version_id, essay_knowledge, knowledge, modelName]):
            return jsonify({"code": 400, "message": "缺少必要参数"}), 400

        try:
            version_id = int(version_id)  # 确保 version_id 是整数
        except ValueError:
            return jsonify({"code": 400, "message": "版本ID必须是整数"}), 400

        # 调用 get_essay_detail 获取作文文本
        essay_content = get_essay_detail(user_id, essay_id, version_id)
        if isinstance(essay_content, tuple):
            return jsonify({"code": essay_content[0], "message": essay_content[1]}), essay_content[0]

        # 调用 service 层获取分析结果
        analysis_data = get_essay_analysis(
            essay_text=essay_content["text"],  # 使用获取的作文文本
            essay_knowledge=essay_knowledge,
            knowledge=knowledge,
            modelName=modelName,
            user_id=user_id,
            essay_id=essay_id,
            version_id=version_id
        )

        if not analysis_data:
            return jsonify({"code": 404, "message": "作文分析数据未找到"}), 404

        # 获取当前时间
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        # 组织返回数据
        response_data = {
            "user_id": user_id,
            "essay_id": essay_id,
            "version_id": version_id,
            "timestamp": timestamp,
            "model_used": modelName,
            "analysis": analysis_data
        }

        return jsonify({
            "code": 200,
            "message": "获取作文分析成功",
            "data": response_data
        }), 200

    except Exception as e:
        print(f"【接口5.1.1】获取单篇作文分析失败：{str(e)}")
        return jsonify({"code": 500, "message": "服务器内部错误"}), 500

# 【接口5.1.1-2】POST /analysis/essay/{essay_id}/{version_id}   获取单篇作文分析
@analysis_routes.route('/analysis/essay2', methods=['POST'])
@token_required
def essay_analysis_api2(user_id):
    """
    作文分析 API
    :param user_id: 用户ID
    :return: 返回作文分析结果（JSON格式）
    """
    try:
        # 解析请求体 JSON
        data = request.get_json()
        if not data:
            return jsonify({"code": 400, "message": "请求体不能为空"}), 400

        # 获取请求参数
        essay_id = data.get("essay_id")
        version_id = data.get("version_id")
        essay_knowledge = data.get("essay_knowledge")
        knowledge = data.get("knowledge")
        modelName = data.get("modelName")

        # 校验必要参数
        if not all([essay_id, version_id, essay_knowledge, knowledge, modelName]):
            return jsonify({"code": 400, "message": "缺少必要参数"}), 400

        try:
            version_id = int(version_id)  # 确保 version_id 是整数
        except ValueError:
            return jsonify({"code": 400, "message": "版本ID必须是整数"}), 400

        # 调用 get_essay_detail 获取作文文本
        essay_content = get_essay_detail(user_id, essay_id, version_id)
        if isinstance(essay_content, tuple):
            return jsonify({"code": essay_content[0], "message": essay_content[1]}), essay_content[0]

        # 调用 service 层获取分析结果
        analysis_data = get_essay_analysis2(
            essay_text=essay_content["text"],  # 使用获取的作文文本
            essay_knowledge=essay_knowledge,
            knowledge=knowledge,
            modelName=modelName,
            user_id=user_id,
            essay_id=essay_id,
            version_id=version_id
        )

        if not analysis_data:
            return jsonify({"code": 404, "message": "作文分析数据未找到"}), 404

        # 获取当前时间
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        # 组织返回数据
        response_data = {
            "user_id": user_id,
            "essay_id": essay_id,
            "version_id": version_id,
            "timestamp": timestamp,
            "model_used": modelName,
            "analysis": analysis_data
        }

        return jsonify({
            "code": 200,
            "message": "获取作文分析成功",
            "data": response_data
        }), 200

    except Exception as e:
        print(f"【接口5.1.1-2】获取单篇作文分析失败：{str(e)}")
        return jsonify({"code": 500, "message": "服务器内部错误"}), 500

#【5.1.2】GET  /analysis/progress   获取进步分析
@analysis_routes.route('/analysis/progress', methods=['GET'])
@token_required
def user_progress_api(user_id):
    try:
        # 获取用户的作文进步分析
        progress_data = get_user_progress(user_id)

        # 如果没有找到进步数据
        if not progress_data:
            return jsonify({"code": 404, "message": "用户没有足够的作文分析数据进行进步对比"}), 404

        return jsonify({
            "code": 200,
            "message": "获取用户进步分析成功",
            "data": progress_data
        }), 200

    except Exception as e:
        print(f"【接口5.1.2】获取进步分析失败: {e}")
        return jsonify({"code": 500, "message": "服务器内部错误"}), 500


#【5.1.3】GET /analysis/compare 对比分析
@analysis_routes.route('/analysis/compare', methods=['GET'])
@token_required
def compare_essays_api(user_id):
    try:
        # 获取请求参数
        essay_id = request.args.get("essay_id")
        version_id_1 = request.args.get("version_id_1")
        version_id_2 = request.args.get("version_id_2")

        if not essay_id or not version_id_1 or not version_id_2:
            return jsonify({"code": 400, "message": "缺少必要参数"}), 400

        # 读取用户的分析数据文件
        file_path = f"../data/raw/analysis_data/{user_id}_analysis.json"
        if not os.path.exists(file_path):
            return jsonify({"code": 404, "message": "分析数据文件不存在"}), 404
        with open(file_path, "r", encoding="utf-8") as file:
            analysis_data = json.load(file)
        if essay_id not in analysis_data:
            return jsonify({"code": 404, "message": "作文 ID 不存在"}), 404

        # 获取该作文的所有版本分析数据
        versions = analysis_data[essay_id]["analysis"]

        # 查找指定的两个版本
        essay_1 = next((v for v in versions if v["version_id"] == version_id_1), None)
        essay_2 = next((v for v in versions if v["version_id"] == version_id_2), None)

        if not essay_1 or not essay_2:
            return jsonify({"code": 404, "message": "指定的版本 ID 不存在"}), 404
        if essay_1.get("model_used") != essay_2.get("model_used"):
            return jsonify({"code": 403, "message": "两个版本使用的评分模型不同，无法进行对比分析"}), 403

        # 进行对比分析
        comparison_result = compare_essays(essay_1, essay_2)
        return jsonify({
            "code": 200,
            "message": "作文版本对比分析成功",
            "data": comparison_result
        }), 200

    except Exception as e:
        print(f"【接口5.1.3】作文对比分析失败：{str(e)}")
        return jsonify({"code": 500, "message": "服务器内部错误"}), 500


#【接口3.1.3评分后处理】
from flask import jsonify, request
from functools import wraps
import logging
from collections import OrderedDict
import json
from flask import jsonify, request
import logging
from pathlib import Path


@analysis_routes.route('/model/postprocess', methods=['POST'])
@token_required
def postprocess_score(user_id):
    """评分后处理接口（精简版）
    返回格式：
    {
        "comments": {
            "fluency": "评语1",
            "grammar": "评语2",
            ...
        }
    }
    """
    try:
        # 1. 获取并验证请求数据
        data = request.get_json()
        if not data or not isinstance(data.get("scoreData"), dict):
            return jsonify({"code": 400, "message": "无效的请求数据"}), 400

        # 2. 加载评分标准
        try:
            with open('standard/details.txt', 'r', encoding='utf-8') as f:
                rating_criteria = json.load(f).get("gpt", [])
        except Exception as e:
            logging.error(f"加载标准失败: {str(e)}")
            return jsonify({"code": 500, "message": "加载评分标准失败"}), 500

        # 3. 评分项映射（英文->中文）
        CRITERIA_MAPPING = {
              "richness":"词汇丰富度",
            "accuracy":"词汇准确性",
            "difficulty":"词汇难度",
            "collocation":"词汇搭配",
            "structure": "句子结构",
            "fluency": "句子流畅性",
            "length":"句子长度",
            "grammar": "语法正确性",
           "paragraph_division":"段落划分",
            "coherence": "段落连贯性",
            "logic":"篇章逻辑",
            "completeness":"篇章完整性",
            "relevance":"内容相关性",
            "depth":"内容深度",
            "novelty":"内容新颖性",
            "logicality":"内容逻辑性"
        }

        # 4. 生成精简评语
        comments = {}
        for eng_name, score in data["scoreData"].items():
            chi_name = CRITERIA_MAPPING.get(eng_name)
            if not chi_name:
                continue

            # 查找匹配的评分标准
            criteria = next((c for c in rating_criteria if c["name"] == chi_name), None)
            if not criteria:
                continue

            try:
                # 获取最接近的评分描述
                score = float(score)
                if "criteria_details" in criteria:
                    best_match = min(
                        criteria["criteria_details"],
                        key=lambda x: abs(float(x["score"]) - score)
                    )
                    comments[eng_name] = best_match["description"]
                else:
                    comments[eng_name] = criteria["description"]
            except (ValueError, KeyError):
                pass

        return jsonify({
            "code": 200,
            "comments": comments
        }), 200

    except Exception as e:
        logging.error(f"处理失败: {str(e)}")
        return jsonify({
            "code": 500,
            "message": "服务器错误",
            "detail": str(e)
        }), 500
#【接口5.1.4】POST /analysis/sum                 #用户当前作文数量统计
from backend.services.analysis_service import count_user_essays
@analysis_routes.route('/analysis/sum', methods=['POST'])
@token_required
def count_user_essays_api(user_id):
    """
    统计指定用户的所有作文数量
    :return: JSON 格式的作文数量统计结果
    """
    try:
        # 获取请求中的用户 ID
        data = request.get_json()
        user_id = data.get("user_id")

        # 校验参数
        if not user_id:
            return jsonify({
                "code": 400,
                "message": "缺少 user_id 参数"
            }), 400

        # 统计作文数量
        essay_count = count_user_essays(user_id)

        return jsonify({
            "code": 200,
            "message": "统计成功",
            "data": {
                "user_id": user_id,
                "essay_count": essay_count
            }
        }), 200

    except Exception as e:
        print(f"【接口5.1.4】统计用户作文数量失败: {e}")
        return jsonify({
            "code": 500,
            "message": "服务器内部错误"
        }), 500


# 【5.1.5】POST /analysis/rank               #当前作文排名百分比
from flask import request, jsonify
from backend.services.analysis_service import get_score_percentile

@analysis_routes.route('/analysis/rank', methods=['POST'])
@token_required
def get_score_percentile_api(user_id):
    """
    获取当前用户作文的排名百分比
    :return: 计算排名百分比的 JSON 响应
    """
    try:
        # 获取请求中的参数
        data = request.get_json()
        essay_id = data.get("essay_id")
        version_id = data.get("version_id")

        # 校验参数
        if not essay_id:
            return jsonify({"code": 400, "message": "缺少 essay_id 参数"}), 400
        if version_id is None:
            return jsonify({"code": 400, "message": "缺少 version_id 参数"}), 400

        # 调用排名计算函数
        return get_score_percentile(user_id, essay_id, version_id)

    except Exception as e:
        print(f"【接口5.1.5】获取作文排名百分比失败: {e}")
        return jsonify({"code": 500, "message": "服务器内部错误"}), 500

# 【接口5.1.6】GET /analysis/vocabulary-diversity 获取作文词汇多样性数据
@analysis_routes.route('/analysis/vocabulary-diversity', methods=['GET'])
@token_required
def get_vocabulary_diversity(user_id):
    try:
        # 获取请求参数
        essay_id = request.args.get('essay_id')
        version_id = request.args.get('version_id')

        if not essay_id or not version_id:
            return jsonify({
                "code": 400,
                "message": "缺少必要参数"
            }), 400

        # 调用 service 层获取词汇多样性分析
        analysis_data = get_vocabulary_diversity_analysis(user_id, essay_id, version_id)

        if not analysis_data:
            return jsonify({
                "code": 404,
                "message": "未找到分析数据"
            }), 404

        return jsonify({
            "code": 200,
            "message": "获取词汇多样性分析成功",
            "data": analysis_data
        }), 200

    except Exception as e:
        print(f"【接口5.1.6】获取词汇多样性分析失败: {e}")
        return jsonify({"code": 500, "message": "服务器内部错误"}), 500

# 【接口5.1.7】GET /analysis/article-structure 获取作文文章结构数据
@analysis_routes.route('/analysis/article-structure', methods=['GET'])
@token_required
def get_article_structure(user_id):
    try:
        # 获取请求参数
        essay_id = request.args.get('essay_id')
        version_id = request.args.get('version_id')

        if not essay_id or not version_id:
            return jsonify({
                "code": 400,
                "message": "缺少必要参数"
            }), 400

        # 调用 service 层获取文章结构分析
        analysis_data = get_article_structure_analysis(user_id, essay_id, version_id)

        if not analysis_data:
            return jsonify({
                "code": 404,
                "message": "未找到分析数据"
            }), 404

        return jsonify({
            "code": 200,
            "message": "获取文章结构分析成功",
            "data": analysis_data
        }), 200

    except Exception as e:
        print(f"【接口5.1.7】获取文章结构分析失败: {e}")
        return jsonify({"code": 500, "message": "服务器内部错误"}), 500

# 【接口5.1.8】GET /analysis/purpose-fit 获取作文目的契合度数据
@analysis_routes.route('/analysis/purpose-fit', methods=['GET'])
@token_required
def get_purpose_fit(user_id):
    try:
        # 获取请求参数
        essay_id = request.args.get('essay_id')
        version_id = request.args.get('version_id')

        if not essay_id or not version_id:
            return jsonify({
                "code": 400,
                "message": "缺少必要参数"
            }), 400

        # 调用 service 层获取目的契合度分析
        analysis_data = get_purpose_fit_analysis(user_id, essay_id, version_id)

        if not analysis_data:
            return jsonify({
                "code": 404,
                "message": "未找到分析数据"
            }), 404

        return jsonify({
            "code": 200,
            "message": "获取目的契合度分析成功",
            "data": analysis_data
        }), 200

    except Exception as e:
        print(f"【接口5.1.8】获取目的契合度分析失败: {e}")
        return jsonify({"code": 500, "message": "服务器内部错误"}), 500

